package com.szwistar.common.datastruct;

import org.apache.mina.core.buffer.IoBuffer;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {
	//protected static final Logger LOG = LoggerFactory.getLogger(Utils.class);

	// HEX 字符索引表
	static char[] HEXCHAR = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

	/**
	 * 字节转换为 HEX 字符串
	 * <p>如：0x3a -> "3A"
	 */
	public static String byteToHexString(byte b) {
		char[] buf = new char[2];
		buf[0] = HEXCHAR[(b >> 4) & 0x0F];
		buf[1] = HEXCHAR[b & 0x0F];
		return new String(buf);
	}

	/**
	  * byte数组转换成十六进制字符串
	  * @param bArray 要转换的字节数组
	  * @param start 起始位置
	  * @param len 要转换的长度
	  * @return HexString
	  */
	public static String bytesToHexString(byte[] bArray, int start, int len) {
		// 非法参数
		if((bArray == null) || (bArray.length < 1) || (start < 0) || (len < 1)) { return ""; }
		// 防止越界
		int stop = Math.min(start+len, bArray.length);
		// 实际长度
		len = stop - start;
		// 非法参数
		if(len < 1) { return ""; }

		char[] buf = new char[2*len];
		byte ch;

		for(int i=0; i<len; i++) {
			ch = bArray[start+i];
			buf[2*i]   = HEXCHAR[(ch >> 4) & 0x0F];
			buf[2*i+1] = HEXCHAR[ch & 0x0F];
		}

		return new String(buf);
	}

	/**
	  * byte数组转换成十六进制字符串
	  * @param bArray 要转换的字节数组
	  * @return HexString
	  */
	public static String bytesToHexString(byte[] bArray) {
		// 非法参数
		if((bArray == null) || (bArray.length < 1)) { return ""; }
		return bytesToHexString(bArray, 0, bArray.length);
	}

	/**
	  * byte数组转换成十六进制字符串
	  * @param bArray 要转换的字节数组
	  * @param start 起始位置
	  * @param len 要转换的长度
	  * @param space 分隔符字符
	  * @return HexString
	  */
	public static String bytesToHexString(byte[] bArray, int start, int len, char space) {
		// 非法参数
		if((bArray == null) || (bArray.length < 1) || (start < 0) || (len < 1)) { return ""; }
		// 防止越界
		int stop = Math.min(start+len, bArray.length);
		// 实际长度
		len = stop - start;
		// 非法参数
		if(len < 1) { return ""; }

		// 最后一个space不插入，所以要减1
		char[] buf = new char[3*len-1];
		byte ch;

		for(int i=0; i<len; i++) {
			ch = bArray[start+i];
			buf[3*i]   = HEXCHAR[(ch >> 4) & 0x0F];
			buf[3*i+1] = HEXCHAR[ch & 0x0F];
			if(i<len-1) { buf[3*i+2] = space; } // 最后一个space不插入
		}

		return new String(buf);
	}

	/**
	  * byte数组转换成十六进制字符串
	  * @param bArray 要转换的字节数组
	  * @param space 分隔符字符
	  * @return HexString
	  */
	public static String bytesToHexString(byte[] bArray, char space) {
		// 非法参数
		if((bArray == null) || (bArray.length < 1)) { return ""; }
		return bytesToHexString(bArray, 0, bArray.length, space);
	}

	public static byte getHexCharValue(byte ch) {
		if((ch >= '0') && (ch <= '9')) {
			ch -= '0';
		} else if((ch >= 'A') && (ch <= 'F')) {
			ch -= 55;
		} else if((ch >= 'a') && (ch <= 'f')) {
			ch -= 87;
		} else {
			throw new RuntimeException("非法的 HEX 字符！");
		}
		return ch;
	}

    /**
	 * 将字符串转成byte数组
	 * @param hexString 要转换的字符串
	 * @return 转换后的byte数组
	 * */
	public static byte[] hexStringToBytes(String hexString) {
		if(Utils.isEmpty(hexString)) { return null; }
		hexString = hexString.trim();
		hexString = hexString.replace(" ", "");
		hexString = hexString.replace("\t", "");
		hexString = hexString.replace(",", "");
		hexString = hexString.replace("0x", "");
		if(hexString.length()%2 != 0) { throw new RuntimeException("HEX字符串长度必须为偶数！"); }

		byte[] buf = hexString.getBytes();
		int len = buf.length/2;
		byte[] retArr = new byte[len];
		byte chh, chl;

		for(int i=0; i<len; i++) {
			chh = getHexCharValue(buf[2*i]);
			chl = getHexCharValue(buf[2*i+1]);
			retArr[i] = (byte)(chh<<4 | chl);
		}

		return retArr;
	}

	/**
	 * byte数组转换成bit字符串(如"1011001")，每个byte代表一个bit，0为0，非0为1
	 */
	public static String bytesToBitString(byte[] bArray) {
		StringBuilder sb = new StringBuilder(bArray.length);
		for (int i = 0; i < bArray.length; i++) {
			if( bArray[i] > 0 ) {
				sb.append("1");
			} else {
				sb.append("0");
			}
			if( i % 8 == 7 ) {
				sb.append(" ");
			}
		}
		return sb.toString();
	}

	/**
	 * 取一个字节数组的一部分
	 * @param bytes 数组
	 * @param start 开始位置
	 * @param len 长度
	 * @return 指定部分的数据
	 */
	public static byte[] bytesSlice(byte[] bytes, int start, int len) {
		byte[] buf = new byte[len];
		System.arraycopy(bytes, start, buf, 0, len);
		return buf;
	}

	/**
	 * 取一个字节数组的一部分
	 * @param bytes 数组
	 * @param start 开始位置
	 * @param flag 结束标志
	 * @param includeFlag 返回数据中是否要包含结束标志本身
	 * @return 指定部分的数据
	 */
	public static byte[] bytesSlice(byte[] bytes, int start, byte[] flag, boolean includeFlag) {
		int pe = bytesIndexOf(bytes, start, flag);
		if(pe < 0) { return new byte[0]; }
		return bytesSlice(bytes, start, pe - start);
	}

	/**
	 * 把多个字节数组拷贝合并成一个大数组
	 */
	public static byte[] bytesMerge(byte[]... bytes) {
		// 累加各数组长度
        int totalSize = 0;
        for (byte[] bs : bytes) { totalSize += bs.length; }
        // 创建合并后的数组
        byte[] totalBytes = new byte[totalSize];
        // 拷贝各个数组的数据
        int size = 0;
        for (byte[] bs : bytes) {
            System.arraycopy(bs, 0, totalBytes, size, bs.length);
            size += bs.length;
        }
        return totalBytes;
    }

	/**
	 * 在一个字节序列中搜索一个子序列
	 * @param bytes 字节序列
	 * @param sub 子序列
	 * @param offset 搜索起始位置
	 * @return 如果搜索到，则返回子序列的开始位置；否则返回 -1
	 */
	public static int bytesIndexOf(byte[] bytes, int offset, byte[] sub) {
		boolean matched;
        for(int pos = offset; pos <= (bytes.length - sub.length); pos++) {
        	matched = true;
        	for(int spos = 0; spos < sub.length; spos++) {
                if(sub[spos] != bytes[pos + spos]) { matched = false; break; }
        	}
        	if(matched) { return pos; }
        }

        return -1;
    }

	/**
	 * 二进制数组比较(c style)
	 * @param a1 数组1
	 * @param a2 数组2
	 * @param len 要比较的长度，此长度必须小于或等于 a1, a2 的长度，否则比较失败！
	 * @return
	 * 	1: a1 大于 a2<br>
	 *  0: 相等<br>
	 *  -1: a1 小于 a2<br>
	 *  >1: 比较失败<br>
	 */
	public static int memcmp(byte[] a1, byte[] a2, int len) {
		if(a1.length < len || a2.length < len) { return Integer.MAX_VALUE; }

		for(int i=0; i<len; i++) {
			if(a1[i] > a2[i]) {
				return 1;
			} else if(a1[i] < a2[i]) {
				return -1;
			}
		}

		return 0;
	}

	public static int memcpy(byte[] dst, byte[] src, int len) {
		System.arraycopy(src, 0, dst, 0, len);
		return len;
	}

	/**
	 * 把 String 拷贝到 byte 数组
	 * @param dst 目标 byte 数组
	 * @param src 源 String
	 * @return 拷贝的字节数。实际字节数以 dst/src 短的那个为准。
	 */
	public static int strcpy(byte[] dst, String src) {
		if(Utils.isEmpty(dst) || Utils.isEmpty(src)) { return 0; }
		byte[] bytes = src.getBytes();
		int len = Math.min(dst.length, bytes.length);
		bzero(dst, null, null);
		return memcpy(dst, bytes, len);
	}

	/**
	 * 把 byte 数组中的字符转换为 String，遇到 '\0' 则结束转换(不包含'\0')
	 */
	public static String cstr(byte[] bytes) {
		if(Utils.isEmpty(bytes)) { return ""; }
		char[] chars = new char[bytes.length];

		int i = 0;
		for(; i<bytes.length; i++) {
			if(bytes[i] == 0) { break; }
			chars[i] = (char) bytes[i];
		}

		return new String(chars, 0, i);
	}

	public static void memset(byte[] bytes, Integer offset, Integer size, byte val) {
		if(Utils.isEmpty(bytes)) { return; }
		if(offset == null) { offset = 0; }
		if(size == null) { size = bytes.length; }
		size = offset + size;
		for(int i = offset; i < size; i++) {
			bytes[i] = val;
		}
	}

	public static void bzero(byte[] bytes, Integer offset, Integer size) {
		memset(bytes, offset, size, (byte)0);
	}

	/**
	 * 把字符串 List 转换为逗号分隔的字符串
	 */
	public static String list2String(List<String> list) {
		if( list == null ) { return null; }
		StringBuilder str = null;

		for( String s : list ) {
			if( str == null ) {
				str = new StringBuilder(s);
			} else {
				str.append(","); str.append(s);
			}
		}

		return str==null ? null : str.toString();
	}

	/**
	 * long 转字节数组(高字节在前)
	 * @return 8 字节数组
	 */
	public static byte[] BElongToBytes(long l) {
        byte[] targets = new byte[8];
        targets[7] = (byte) (l       & 0xFF);
        targets[6] = (byte) (l >> 8  & 0xFF);
        targets[5] = (byte) (l >> 16 & 0xFF);
        targets[4] = (byte) (l >> 24 & 0xFF);
        targets[3] = (byte) (l >> 32 & 0xFF);
        targets[2] = (byte) (l >> 40 & 0xFF);
        targets[1] = (byte) (l >> 48 & 0xFF);
        targets[0] = (byte) (l >> 56 & 0xFF);
        return targets;
    }

	/**
	 * long 整数转字节数组(低字节在前)
	 * @return 8 字节数组
	 */
	public static byte[] LElongToBytes(long l) {
        byte[] targets = new byte[8];
        targets[0] = (byte) (l       & 0xFF);
        targets[1] = (byte) (l >> 8  & 0xFF);
        targets[2] = (byte) (l >> 16 & 0xFF);
        targets[3] = (byte) (l >> 24 & 0xFF);
        targets[4] = (byte) (l >> 32 & 0xFF);
        targets[5] = (byte) (l >> 40 & 0xFF);
        targets[6] = (byte) (l >> 48 & 0xFF);
        targets[7] = (byte) (l >> 56 & 0xFF);
        return targets;
    }

	/**
	 * int整数转 4 字节数组(高字节在前)
	 */
	public static byte[] BEintToBytes(int i) {
        byte[] targets = new byte[4];
        targets[3] = (byte) (i & 0xFF);
        targets[2] = (byte) (i >> 8 & 0xFF);
        targets[1] = (byte) (i >> 16 & 0xFF);
        targets[0] = (byte) (i >> 24 & 0xFF);
        return targets;
    }

	/**
	 * int整数转 4 字节数组(低字节在前)
	 */
	public static byte[] LEintToBytes(int i) {
        byte[] targets = new byte[4];
        targets[0] = (byte) (i & 0xFF);
        targets[1] = (byte) (i >> 8 & 0xFF);
        targets[2] = (byte) (i >> 16 & 0xFF);
        targets[3] = (byte) (i >> 24 & 0xFF);
        return targets;
    }

	/**
	 * short 整数转 2 字节数组(高字节在前)
	 */
	public static byte[] BEshortToBytes(short s) {
        byte[] targets = new byte[2];
        targets[1] = (byte) (s & 0xFF);
        targets[0] = (byte) (s >> 8 & 0xFF);
        return targets;
    }

	/**
	 * short 整数转 2 字节数组(低字节在前)
	 */
	public static byte[] LEshortToBytes(short s) {
        byte[] targets = new byte[2];
        targets[0] = (byte) (s & 0xFF);
        targets[1] = (byte) (s >> 8 & 0xFF);
        return targets;
    }

	/**
	 * byte 数组中取2字节，转换为 short 数值(高字节在前)
	 */
	public static short bytesToShort(byte[] raw, int offset) {
		int len = Math.min(2, raw.length-offset);
		long ret = 0;
		for(int i=0; i<len; i++) {
			ret = (ret << 8) | (raw[offset+i] & 0xFF);
		}
		return (short)ret;
	}

	/**
	 * byte 数组中取4字节，转换为 int 数值(高字节在前)
	 */
	public static int bytesToInt(byte[] raw, int offset) {
		int len = Math.min(4, raw.length-offset);
		long ret = 0;
		for(int i=0; i<len; i++) {
			ret = (ret << 8) | (raw[offset+i] & 0xFF);
		}
		return (int)ret;
	}

	/**
	 * byte 数组中取 8 字节，转换为 int 数值(高字节在前)
	 */
	public static long bytesToLong(byte[] raw, int offset) {
		int len = Math.min(8, raw.length-offset);
		long ret = 0;
		for(int i=0; i<len; i++) {
			ret = (ret << 8) | (raw[offset+i] & 0xFF);
		}
		return ret;
	}

	/**
	 * 求 byte 数组的异或和
	 */
	public static byte xorsum8(byte[] data, int offset, int len) {
		char xor = (char)data[offset];
		for( int i=1; i<len; i++ ) {
			xor ^= (char)data[offset+i];
		}
		return (byte) xor;
	}

	/**
	 * 计算异或和
	 */
	public static byte xorsum8(IoBuffer buffer, int offset, int len) {
		byte xorsum = 0;
		for(int i=0; i<len; i++) {
			xorsum ^= buffer.get(offset+i);
		}
		return xorsum;
	}

	/**
	 * 计算累加和
	 */
	public static byte sum8(IoBuffer buffer, int offset, int len) {
		byte xorsum = 0;
		for(int i=0; i<len; i++) {
			xorsum += buffer.get(offset+i);
		}
		return xorsum;
	}

	/**
	 * 将int数组转成字符串
	 * @param arrs 要转换的数组
	 * @param splitter 分割符
	 * */
	public static String intArrToString(int[] arrs, String splitter) {
		if(arrs == null || arrs.length == 0) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < arrs.length - 1; i++) {
			sb.append(arrs[i]);
			sb.append(splitter);
		}
		sb.append(arrs[arrs.length - 1]);
		return sb.toString();
	}

	/**
	 * 按指定表达式分解字符串，但去掉空的部分
	 * @param str 字符串
	 * @param regex 分隔正则表达式
	 * @return 子字符串
	 * @see String#split(String)
	 */
	public static String[] split(String str, String regex) {
		String[] parts = str.split(regex);

		// 统计非空的数量
		int count = 0;
		for(String part: parts) {
			if(part.length() != 0) { count++; }
		}

		// 保存并返回非空的
		String[] ret = new String[count];
		count = 0;
		for(String part: parts) {
			if(part.length() != 0) { ret[count++] = part; }
		}
		return ret;
	}

	/**
	 * 将字符串转成int数组
	 * @param str: 要转换的字符串
	 * @param regex: 分隔符
	 * */
	public static int[] stringToIntArr(String str, String regex) throws NumberFormatException {
		String [] strArr = str.split(regex);
		int [] retArr = new int[strArr.length];
		for(int i = 0; i < strArr.length; i++) {
			retArr[i] = Integer.parseInt(strArr[i]);
		}
		return retArr;
	}

	public static boolean stringsCompare(String[] str1, String[] str2, boolean ignoreCase) {
		if(str1 == null || str2 == null || str1.length != str2.length) { return false; }
		for(int i = 0; i < str1.length; i++) {
			if(ignoreCase) {
				if(!str1[i].equalsIgnoreCase(str2[i])) { return false; }
			} else {
				if(!str1[i].equals(str2[i])) { return false; }
			}
		}
		return true;
	}

	public static Exception newException(String message, Object... args) {
		if(message == null) {
			message = "";
		} else if(args != null) {
			message = String.format(message, args);
		}

		return new Exception(message);
	}

	public static RuntimeException newRuntimeException(String message, Object... args) {
		if(message == null) {
			message = "";
		} else if(args != null) {
			message = String.format(message, args);
		}

		return new RuntimeException(message);
	}

	/**
	 * 判断任意两个对象是否相等
	 */
	public static boolean eq(Object a, Object b) {
		if(a == null && b == null) { return true; }
		if(a == null || b == null) { return false; }
		if(!isAssignableFrom(a.getClass(), b.getClass())) { return false; }
		return a.equals(b);
	}

	/**
	 * 判断对象是否为空
	 * @param obj 对象
	 * @return {@code true}: 为空<br>{@code false}: 不为空
	 */
	public static boolean isEmpty(Object obj) {
		if (obj == null) {
			return true;
		}
		if (obj instanceof String) {
			return (((String)obj).trim().length() == 0);
		}
		if (obj.getClass().isArray()) {
			return (Array.getLength(obj) == 0);
		}
		if (obj instanceof Collection<?>) {
			return ((Collection<?>) obj).isEmpty();
		}
		if (obj instanceof Map<?,?>) {
			return ((Map<?,?>) obj).isEmpty();
		}
		return false;
	}

    /**
     * 判断对象是否非空
     * @param obj 对象
     * @return {@code true}: 非空<br>{@code false}: 空
     */
    public static boolean isNotEmpty(Object obj) {
        return !isEmpty(obj);
    }

	/**
	 * IP地址转换: int型 -> 字符串型
	 */
	public static String ipInt2Str(int intIp) {
		StringBuilder builder = new StringBuilder();
		builder.append(intIp & 0xFF).append(".");
		builder.append((intIp >> 8) & 0xFF).append(".");
		builder.append((intIp >> 16) & 0xFF).append(".");
		builder.append((intIp >> 24) & 0xFF);
		return builder.toString();
	}

	/**
	 * IP地址转换: 字符串型 -> int型
	 */
	public static Integer ipStr2Int(String str) {
    	if(isEmpty(str)) { return null; }

		String[] parts = str.split("\\.");
		if(parts.length != 4) { return null; }

		try {
			int p1 = Integer.parseInt(parts[0]);
			int p2 = Integer.parseInt(parts[1]);
			int p3 = Integer.parseInt(parts[2]);
			int p4 = Integer.parseInt(parts[3]);
			return (p1<<24 | p2<<16 | p3<<8 | p4);
		} catch(Exception e) {
			return null;
		}
	}

	public static String ipBytes2Str(byte[] bytes) {
		return String.format("%d.%d.%d.%d", bytes[0]&0xFF, bytes[1]&0xFF, bytes[2]&0xFF, bytes[3]&0xFF);
	}

	public static byte[] ipStr2Bytes(String str) {
    	if(isEmpty(str)) { return null; }

		String[] parts = str.split("\\.");
		if(parts.length != 4) { return null; }

		try {
			byte[] bytes = new byte[4];
			bytes[0] = (byte) Integer.parseInt(parts[0]);
			bytes[1] = (byte) Integer.parseInt(parts[1]);
			bytes[2] = (byte) Integer.parseInt(parts[2]);
			bytes[3] = (byte) Integer.parseInt(parts[3]);
			return bytes;
		} catch(Exception e) {
			return null;
		}
	}

	public static boolean isIpAddr(String str) {
		return ipStr2Int(str) != null;
	}

	/**
	 * 版本比较
	 * @param v1 "m.n.bbb"形式的版本号
	 * @param v2 "m.n.bbb"形式的版本号
	 * @return >0 大于, =0 等于, <0 小于
	 */
	public static int versionCompare(String v1, String v2) {
		String[] sv1 = v1.split("\\.");
		String[] sv2 = v2.split("\\.");

		int ivm1 = Integer.parseInt(sv1[0]);
		int ivn1 = Integer.parseInt(sv1[1]);
		int ivb1 = Integer.parseInt(sv1[2]);
		int ivm2 = Integer.parseInt(sv2[0]);
		int ivn2 = Integer.parseInt(sv2[1]);
		int ivb2 = Integer.parseInt(sv2[2]);

		if(ivm2 != ivm1) { return ivm1-ivm2; }
		if(ivn2 != ivn1) { return ivn1-ivn2; }
		if(ivb2 != ivb1) { return ivb1-ivb2; }
		return 0;
	}

    public static short makeShort(byte hi, byte low) {
    	return (short)(hi<<8 | low);
    }

    public static byte hibyte(short val) {
    	return (byte)((val >> 8) & 0xFF);
    }

    public static byte lobyte(short val) {
    	return (byte)(val & 0xFF);
    }

    /**
     * 判断是否是数字(可以相互赋值)
     */
    public static boolean isNumber(Class<?> clazz) {
    	return clazz.equals(int.class) || clazz.equals(Integer.class) ||
    			clazz.equals(long.class) || clazz.equals(Long.class) ||
    			clazz.equals(float.class) || clazz.equals(Float.class) ||
    			clazz.equals(double.class) || clazz.equals(Double.class) ||
    			clazz.equals(byte.class) || clazz.equals(Byte.class) ||
				clazz.equals(char.class) || clazz.equals(Character.class);
    }

    /**
     * 判断是否是布尔类型(可以相互赋值)
     */
    public static boolean isBoolean(Class<?> clazz) {
    	return clazz.equals(boolean.class) || clazz.equals(Boolean.class);
    }

    /**
     * 判断是否是布尔类型值
     */
    public static boolean isBooleanValue(Object obj) {
    	return (obj != null) && isBoolean(obj.getClass());
    }

    /**
     * 判断是否是void类型(可以相互赋值)
     */
    public static boolean isVoid(Class<?> clazz) {
    	return clazz.equals(void.class) || clazz.equals(Void.class);
    }

    /**
     * 判断 target = source 是否可行
     * @param target 被赋值的类
     * @param source 用于赋值的类
     */
    public static boolean isAssignableFrom(Class<?> target, Class<?> source) {
    	return target.isAssignableFrom(source) ||
    			(isVoid(target) && isVoid(source)) ||
    			(isNumber(target) && isNumber(source)) ||
    			(isBoolean(target) && isBoolean(source));
    }

	/**
	 * 把字符串转换成指定的类型值
	 * @param clazz 指定的类型
	 * @param str 要转换的字符串
	 * @return 转换后的类型值
	 */
	public static Object parseValue(Class<?> clazz, String str) throws Exception {
		if(clazz.equals(String.class)) {
			return str;
		} else if(clazz.equals(int.class) || clazz.equals(Integer.class)) {
			return Integer.parseInt(str);
		} else if(clazz.equals(long.class) || clazz.equals(Long.class)) {
			return Long.parseLong(str);
		} else if(clazz.equals(float.class) || clazz.equals(Float.class)) {
			return Float.parseFloat(str);
		} else if(clazz.equals(double.class) || clazz.equals(Double.class)) {
			return Double.parseDouble(str);
		} else if(clazz.equals(byte.class) || clazz.equals(Byte.class)) {
			return Byte.parseByte(str);
		} else if(clazz.equals(char.class) || clazz.equals(Character.class)) {
			return str.charAt(0);
		} else if(clazz.equals(boolean.class) || clazz.equals(Boolean.class)) {
			str = str.trim();
			if(str.equalsIgnoreCase("TRUE") || str.equalsIgnoreCase("ON") || str.equalsIgnoreCase("YES") || str.equalsIgnoreCase("Y") || str.equalsIgnoreCase("OK")) {
				return true;
			} else if(str.equalsIgnoreCase("FALSE") || str.equalsIgnoreCase("OFF") || str.equalsIgnoreCase("NO") || str.equalsIgnoreCase("N") || str.equalsIgnoreCase("Fail")) {
				return false;
			} else {
				throw new IllegalArgumentException("Illegal boolean expression: " + str);
			}
		}

		// 尝试查找参数类中符合如下声明的构造函数，并调用它来解析指定字符串并生成参数对象
		// public XxxType(String str);
		try {
			Constructor<?> constructor = clazz.getConstructor(String.class);
			return constructor.newInstance(str);
		} catch(NoSuchMethodException e) {
			// 没有对应的构造函数
		}

		// 尝试查找参数类中符合如下声明的静态函数，并调用它来解析指定字符串
		// public static XxxType parse(String str);
		List<Method> methods = Reflector.getMethods(clazz, true, "parse", clazz, String.class);
		if(!isEmpty(methods)) {
			return methods.get(0).invoke(null, str);
		}

		throw new IllegalArgumentException("Unsupport type: " + clazz.getSimpleName());
	}

	/** 转换成 Double 类型 */
	public static Double toDouble(Object val) {
		if(val == null) return null;
		if(val instanceof String) return Double.parseDouble(val.toString());

		if(val instanceof Number) {
			Number val2 = (Number)val;
			return val2.doubleValue();
		}
		if(val instanceof Character) {
			Character val2 = (Character)val;
			int val3 = val2;
			return (double)val3;
		}
		return null;
	}

    /** 生成位于 (min, max) 之间的随机数 */
    public static double random(double min, double max) {
    	return min + Math.random()*(max - min);
    }
	/** 生成位于 (min, max) 之间的随机数 */
    public static long random(long min, long max) {
    	return Math.round(random((double)min, (double)max));
    }
	/** 生成位于 (min, max) 之间的随机数 */
    public static int random(int min, int max) {
    	return (int)Math.round(random((double)min, (double)max));
    }

    /**
     * 生成随机字符串
     * @param len 字符串长度
     * @param rangeChars 随机字符串取值范围，如果为空，则默认为[0-9a-zA-Z]
     */
    public static String randomString(int len, String rangeChars) {
    	if(rangeChars == null) { rangeChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
    	int rlen = rangeChars.length() - 1;
    	char[] buf = new char[len];
    	for(int i=0; i<len; i++) {
        	buf[i] = rangeChars.charAt(random(0, rlen));
    	}
		return new String(buf);
    }

    /**
     * 正则表达式匹配
     * @param regex 正则表达式
     * @param str 字符串
     * @return 匹配的结果; [0] 是整个表达式匹配结果；其它是子匹配结果
     */
    public static String[] match(final String regex, String str) {
		return match(Pattern.compile(regex), str);
	}

    /**
     * 正则表达式匹配
     * @param pattern 正则表达式
     * @param str 字符串
     * @return 匹配的结果; [0] 是整个表达式匹配结果；其它是子匹配结果
     */
	public static String[] match(final Pattern pattern, String str) {
		Matcher matcher = pattern.matcher(str);
		if(!matcher.find()) { return null; }

		String[] params = new String[1 + matcher.groupCount()];
		for(int i=0; i<params.length; i++) {
			params[i] = str.substring(matcher.start(i), matcher.end(i));
		}
		return params;
	}

	// For test only
	@SuppressWarnings("unused")
	public static void main(String[] args) throws Exception {
		boolean ret;
		ret = isAssignableFrom(Long.class, Byte.class);		// true
		ret = isAssignableFrom(Boolean.class, boolean.class);	// true
		ret = isAssignableFrom(Object.class, Long.class);		// true
		ret = isAssignableFrom(Long.class, Object.class);		// false
		System.out.println(randomString(16, null));
		System.out.println(random(0, 0));
	}
}
